<template>
  <div class="page-container relative">
    <BaseCollapse title="基础信息">
      <DynamicForm :config="dyConfig" :questions="dyQuestions" ref="baseRef" />
    </BaseCollapse>
    <BaseCollapse title="盘点原因">
      <DynamicForm :config="dyReasonConfig" :questions="dyReasonQuestions" ref="reasonRef" />
    </BaseCollapse>
    <BaseCollapse title="盘点任务">
      <DynamicForm :config="dyTaskConfig" :questions="dyTaskQuestions" ref="taskRef" />
    </BaseCollapse>
    <BaseCollapse v-if="['CHECK'].includes(state.showType)" title="盘点清单">
      <div class="space-x-2 mb-4">
        <a-button type="primary" @click="handleOut">
          <template #icon><FileOutlined /></template>导出盘点清单
        </a-button>
        <a-button type="primary" @click="handleImport">
          <template #icon><ImportOutlined /></template>导入盘点结果
        </a-button>
      </div>
      <DynamicTable :config="dyListConfig" :tables="dyListTable" ref="listRef"></DynamicTable>
    </BaseCollapse>
    <BaseCollapse v-if="['VIEW'].includes(state.showType)" title="盘点结果">
      <DynamicTable :tables="dyTable" :config="dyTableConfig" :icons="dyIcons" ref="fileRef">
        <template #fileCodes="{ record }">
          {{ fileCodesName(record.fileCodes) }}
        </template>
      </DynamicTable>
    </BaseCollapse>
    <!-- 异常清单，无异常数据则隐藏列表 -->
    <BaseCollapse v-if="['ERROR', 'VIEW'].includes(state.showType) && state.showErrorTable" title="盘点异常清单">
      <DynamicForm :config="dyErrorConfig" :questions="dyErrorQuestions" ref="errorRef" />
    </BaseCollapse>
    <!-- <BaseCollapse v-if="['AUDIT'].includes(state.showType)" title="审批意见">
      <DynamicForm :config="dyCommentConfig" :questions="dyCommentQuestions" ref="commentRef" />
    </BaseCollapse> -->
    <ApprovalDetail v-if="['VIEW', 'AUDIT'].includes(state.showType) && query.processInstanceId" :config="approvalConfig" @back="approvalGoBack"></ApprovalDetail>
    <div class="space-x-2 w-full text-center my-4">
      <a-button v-if="state.showType !== 'AUDIT'" @click="cancel">返回</a-button>
      <a-button v-if="['ADD', 'EDIT', 'CHECK', 'ERROR'].includes(state.showType)" @click="submit(0)">暂存</a-button>
      <a-button v-if="['ADD', 'CHECK', 'ERROR', 'EDIT'].includes(state.showType)" type="primary" @click="submit(1)">提交</a-button>
      <a-button v-if="['VIEW'].includes(state.showType) && [1, 3].includes(state.archiveStatus)" type="primary" @click="handleEdit">编辑</a-button>
    </div>
    <!-- 详细盘点结果 -->
    <InventoryResult v-model:visible="state.showDetail" v-if="state.showDetail" :show-id="state.showId" />
  </div>
</template>
<script lang="ts" setup>
import { getCurrentInstance, onBeforeUnmount, onMounted, reactive, ref } from 'vue';
import { DynamicForm, DynamicTable } from '@/components/public-template';
import AuditRecord from '@/components/common/AuditRecord/index.vue';
import ApprovalDetail from '@/components/approval-details/index.vue';
import BaseCollapse from '@/components/common/BaseCollapse/index.vue';
import InventoryResult from './components/inventoryResult.vue';
import indexService from './index.service';
import { useRoute, useRouter } from 'vue-router';
import { inventoryAudit, inventoryAutoProduct, inventoryConfirm, inventoryException, inventoryGet, inventorySave, subjectListSimple } from '@/config/api/archivesFileInventory';
import { message } from 'ant-design-vue';
import { Api } from '@/config/api/archivesFileInventory';
import { Api as ApiFile } from '@/config/api/archivesFile';
import { DYNAMICLAYERUPLOAD, DYNAMICLOCALICONS } from '@/mixins/subject/subject-types';
import { downloadFile } from '@/utils/useDownload';
import { filter } from 'rxjs/operators';
import { throttle } from 'xe-utils';
import { Item } from 'ant-design-vue/lib/menu';

const { query } = useRoute();

const state = reactive({
  showType: 'ADD', // enum 'ADD' 'VIEW' 'AUDIT' 'CHECK' 'ERROR'
  archiveStatus: null, // 档案状态
  showDetail: false,
  showId: null,
  showErrorTable: true // 是否显示异常清单
});
const baseRef = ref(null);
const reasonRef = ref(null);
const taskRef = ref(null);
const listRef = ref(null);
const errorRef = ref(null);
const commentRef = ref(null);
const route = useRoute();
const router = useRouter();
state.showType = route.query.showType as string;

const approvalConfig: any = ref({
  title: '审批流程',
  showBackBtn: true, //显示返回按钮
  showAgreeBtn: true, //显示同意按钮
  showGoBackBtn: true, // 显示退回按钮
  showRejectBtn: true // 显示拒绝按钮
});

const approvalGoBack = (cb: any) => {
  cb?.();
};
const dyConfig: any = {
  labelCol: 8,
  wrapperCol: 16,
  grid: 6,
  layout: 'vertical',
  cancelSave: true
};
const dyReasonConfig: any = {
  labelCol: 8,
  wrapperCol: 16,
  grid: 6,
  layout: 'vertical',
  cancelSave: true
};
const dyTaskConfig: any = {
  queryUrl: Api.inventoryGetTaskList,
  protType: 'post',
  idAsName: 'billId',
  cancelSave: true,
  beforeWithMethod: (data) => {
    if (!Array.isArray(data)) return [];
    return {
      inventoryTasks: ['ADD', 'EDIT'].includes(state.showType)
        ? data.map((item) => ({
            ...item,
            inventoryRange: Array.isArray(item.inventoryRange) ? item.inventoryRange.map((obj) => obj.id) : null,
            fileType: Array.isArray(item.fileType) ? item.fileType.map((obj) => obj.id) : null
          }))
        : data.map((item) => ({
            ...item,
            inventoryRange: Array.isArray(item.inventoryRange) ? item.inventoryRange.map((obj) => obj.name).join(', ') : null,
            fileType: Array.isArray(item.fileType) ? item.fileType.map((obj) => obj.name).join(', ') : null
          }))
    };
  }
};
const dyListConfig: any = {
  queryUrl: Api.inventoryList,
  protType: 'post',
  params: { id: route.query.id },
  cancelSave: true,
  scroll: {
    x: 3000
  },
  beforeWithMethod: (data) => {
    if (!Array.isArray(data)) return null;
    let list = [];
    if (['CHECK', 'EDIT'].includes(state.showType)) {
      list = data.map((item) => ({
        ...item,
        filesBoxCode: item.archivesFileList.filesBoxCode,
        name: item.archivesFileList.name,
        code: item.archivesFileList.code,
        fileCode: item.archivesFileList.fileCode,
        filePages: item.archivesFileList.filePages,
        retentionPeriodDate: item.archivesFileList.retentionPeriodDate
      }));
    } else {
      list = data.map((item) => ({
        ...item
      }));
    }
    return list;
  }
};
const dyErrorConfig: any = {
  name: 'errorTable',
  queryUrl: Api.inventoryExceptionList,
  protType: 'post',
  cancelSave: true,
  beforeWithMethod: (data) => {
    if (!data || data.length == 0) state.showErrorTable = false;
    if (!Array.isArray(data)) return null;
    return {
      fileListVoList: data.map((item) => ({
        ...item,
        filesBoxCode: item.archivesFileList.filesBoxCode,
        name: item.archivesFileList.name,
        code: item.archivesFileList.code,
        fileCode: item.archivesFileList.fileCode,
        filePages: item.archivesFileList.filePages,
        retentionPeriodDate: item.archivesFileList.retentionPeriodDate,
        archivesFileList: [
          {
            ...item.archivesFileList,
            boxCode: item.boxCode,
            typeName: item.typeName
          }
        ]
      }))
    };
  }
};
const dyTableConfig: any = {
  name: 'inventoryResultTable',
  queryUrl: Api.inventoryResult,
  protType: 'post',
  params: {
    id: route.query.id
  }
};
const dyCommentConfig: any = {
  labelCol: 8,
  wrapperCol: 22,
  grid: 6,
  layout: 'vertical',
  cancelSave: true
};
const { proxy }: any = getCurrentInstance();
const dyQuestions: any = reactive(indexService.getQuestions());
const dyReasonQuestions: any = reactive(['ADD', 'EDIT'].includes(state.showType) ? indexService.getReasonQuestions() : indexService.getViewReasonQuestions());
const dyTaskQuestions: any = reactive(['ADD', 'EDIT'].includes(state.showType) ? indexService.getTaskQuestions() : indexService.getViewTaskQuestions());
const dyListTable: any = reactive(indexService.getListTables());
const dyTable: any = reactive(indexService.getTables());
const dyIcons: any = reactive(indexService.getIcons());
const dyErrorQuestions: any = reactive(indexService.getErrorQuestions({ showType: state.showType }));
const dyCommentQuestions: any = reactive(indexService.getCommentQuestions({ showType: state.showType }));

onMounted(() => {
  if (state.showType == 'ADD') {
    inventoryAutoProduct(null).then((result) => {
      if (result.success) {
        // 基本信息
        const data = result.data;
        dyQuestions.forEach((item) => (item.value = data[item.key]));
      }
    });
  } else if (['AUDIT', 'CHECK', 'ERROR', 'VIEW', 'EDIT'].includes(state.showType)) {
    inventoryGet(route.query.id).then((result) => {
      if (result.success) {
        // // 基本信息
        const data = result.data;
        state.archiveStatus = result.data.status;
        dyQuestions.forEach((item) => (item.value = data[item.key]));
        // 盘点原因
        dyReasonQuestions.forEach((item) => (item.value = data[item.key]));
      }
    });
  }
  if (['VIEW'].includes(state.showType)) {
    approvalConfig.value.showBackBtn = false;
    approvalConfig.value.showAgreeBtn = false;
    approvalConfig.value.showGoBackBtn = false;
    approvalConfig.value.showRejectBtn = false;
  }
});

// 监听table
const subscribeSub = proxy.$NotificationPubSub
  .getParams()
  .pipe(filter((res) => res !== 0))
  .subscribe((item: any) => {
    if (item.key === DYNAMICLOCALICONS) {
      state.showId = route.query.id;
      state.showDetail = true;
    }
  });

function cancel() {
  router.go(-1);
}

function fileCodesName(data) {
  if (!data?.length) {
    return '';
  }
  return data.join(',');
}
function handleEdit() {
  router
    .replace({
      name: 'ArchivesManageAddCheck',
      query: {
        id: route.query.id,
        showType: 'EDIT'
      }
    })
    .then(() => {
      router.go(0);
    });
}
// 提交 op操作（0=暂存；1=提交）
const submit = throttle(async function (op) {
  if (['ADD', 'EDIT'].includes(state.showType)) {
    const taskData = taskRef.value.getDataFrom();
    const boolean = taskData.inventoryTasks.every((item) => {
      return new Date(item.startInventoryTime) <= new Date(item.expirationReminder);
    });
    if (!boolean) {
      return message.warning('结束时间须大于等于开始时间');
    }
  }
  if (['ADD', 'EDIT'].includes(state.showType)) {
    // 基本信息
    const baseData = baseRef.value.getDataFrom();
    // 盘点原因
    let isError;
    await reasonRef.value.isValidateFields(op == 0 ? [] : null).catch((error) => {
      isError = true;
      console.warn(error);
    });
    const reasonData = reasonRef.value.getDataFrom();
    taskRef.value.onFinish((taskData) => {
      console.log('taskData', taskData);
      const params = {
        op,
        ...baseData,
        ...reasonData,
        ...taskData
      };
      state.showType == 'EDIT' && Object.assign(params, { id: route.query.id });
      console.log('params', params);
      if (isError) return;
      inventorySave(params).then((result) => {
        if (result.success) {
          message.success('提交成功');
          router.go(-1);
        }
      });
    }, op == 0);
  } else if (state.showType == 'AUDIT') {
    const commentData = commentRef.value.getDataFrom();
    const params = {
      billId: route.query.id,
      ...commentData
    };
    inventoryAudit(params).then((result) => {
      if (result.success) {
        message.success('提交成功');
        router.go(-1);
      }
    });
  } else if (state.showType == 'CHECK') {
    listRef.value.onFinish((listData) => {
      const fileListVoList = listData.map((item) => ({
        id: item.id,
        inventoryResult: item.inventoryResult,
        resultExplain: item.resultExplain
      }));
      const params = {
        billId: route.query.id,
        fileListVoList,
        opt: op
      };
      if (fileListVoList.some((item) => item.inventoryResult == 2 && !item.resultExplain)) return message.warning('不通过时【说明】必填');
      console.log('params', params);
      inventoryConfirm(params).then((result) => {
        if (result.success) {
          message.success('提交成功');
          router.go(-1);
        }
      });
    }, op == 0);
  } else if (state.showType == 'ERROR') {
    errorRef.value.onFinish((listData) => {
      const fileListVoList = listData.fileListVoList.map((item) => ({
        id: item.id,
        exceptionHandling: item.exceptionHandling
      }));
      const params = {
        billId: route.query.id,
        fileListVoList,
        opt: op
      };
      inventoryException(params).then((result) => {
        if (result.success) {
          message.success('提交成功');
          router.go(-1);
        }
      });
    }, op == 0);
  }
}, 3000);
// 导出盘点清单
async function handleOut() {
  const url = `${Api.inventoryExportList}/${route.query.id}`;
  await downloadFile(url);
  message.success('导出成功');
}
// 导入盘点结果
function handleImport() {
  proxy.$NotificationPubSub.pushParams({
    key: DYNAMICLAYERUPLOAD,
    value: {
      state: {
        url: `${Api.inventoryImport}/${route.query.id}`,
        downloadUrl: ApiFile.fileGetImportTemplate,
        downloadProtType: 'post',
        downloadParams: { templateCode: 'archives_inventory_file_list' },
        downloadHeader: true,
        downloadName: '下载导入模板',
        downloadFileName: '档案盘点清单导入',
        downloadRule: '仅允许上传excel格式；文件大小不超过10M',
        hideMessage: true,
        callback: (res) => {
          handleCheckImport && handleCheckImport(res);
        }
      }
    }
  });
}
// 获取盘点负责人列表
// function getInventoryList() {
//   subjectListSimple({}).then((res) => {
//     if (res.success) {
//       const option = res.data.map((item) => ({ label: item.nickName, value: item.nickName, key: item.id }));
//       dyTaskQuestions.forEach((item) => {
//         item.state.columns[5].options = option;
//       });
//     }
//   });
// }
// 处理导入盘点结果
function handleCheckImport(res) {
  res.message[0] ? message.warning({ content: res.message[0], duration: 6 }) : message.success('上传成功！');
  listRef.value.dataList.value.forEach((item) => {
    const obj = res.list.find((daItem) => daItem.filesBoxCode == item.filesBoxCode) || {};
    item.inventoryResult = obj.inventoryResult;
    item.resultExplain = obj.resultExplain;
  });
}

onBeforeUnmount(() => {
  subscribeSub && subscribeSub.unsubscribe();
  proxy.$NotificationPubSub.clearParams();
});
</script>

<style lang="less" scoped>
:deep(.ant-form-item-control-input-content) {
  word-wrap: break-word;
}
</style>
